var data;
var display_level = ['', 'easy', 'medium', 'hard', 'random'];
var menu = [];

//add question
function add(){
    window.location.href = '../html/addquestion.html'
}

//get login username
function getName(){
    var title = document.getElementById("title4");
    title.innerHTML = 'Hi ' + localStorage.getItem("UserName") + '! Here is the question list:';
}

//show question list
function getTable() {
    var details = data.detail;
    var htmlStr = "";   
    
    for(var i = 0;i < details.length;i++) {
        var detail = details[i];
        htmlStr += "<tr>";
        htmlStr += "<td>" + detail.category + "</td>";
        htmlStr += "<td>" + display_level[detail.level] + "</td>";
        htmlStr += "<td>" + (detail.property == 0 ? 'public' : 'private') + "</td>";
        htmlStr += "<td>" + detail.question + "</td>";
        htmlStr += "<td>" + detail.answer + "</td>";
        htmlStr += "<td>" + '<button class="btn btn-info" type="button" onclick="update(' + i + ')">update</button> '+ "</td>";
        htmlStr += "<td>" + '<button class="btn btn-danger" type="button" onclick="deleteQuz(' + i + ')">delete</button> '+ "</td>";
        htmlStr += "</tr>";
        
        }
    document.getElementById("tBody").innerHTML = htmlStr;
    document.getElementById("count").innerText = data.total;
}

//search question
function search(){
    var category = document.getElementById("category_select").value;
    var level = document.getElementById("difficulty_level").value;
    var Property = document.getElementById("Property").value;
    var tag = document.getElementById('tag').value;

    var params = new URLSearchParams();
    if(!isEmptyStr(category)){
        params.append('category', category);
    }
    if(!isEmptyStr(level)){
        params.append('level', level);
    }
    if(!isEmptyStr(tag)){
        params.append('tag', tag);
    }
    params.append('property', Property);
    
    var url = '../php/searchQuestion.php?' + params.toString();

    
    ajaxRequest(url, 'get', null, function(){
        console.log(this.responseText);
        let json_object = JSON.parse(this.responseText);
        basicdata = json_object.basic;
        data = json_object;
        getTable();
    }, function(){
        console.log(this.responseText);
        alert("Something wrong with search question");
    });

    
}

function isEmptyStr(str){
    if (str == 'undefined' || !str || !/[^\s]/.test(str)) {
        return true
    } else {
        return false;
    }
}

//modify question
function update(index) { 
    localStorage.setItem('question_detail',JSON.stringify(data.detail[index]));
    window.location.href = '../html/updatequestion.html';
}

//delete questions
function deleteQuz(index) {
    let $qid = data.detail[index].id;
    let postdata = {quzid:$qid}; 
    function ok(){
        alert("Delete question "+ $qid +" successfully!");
        search();
    }
    function ko(){
        alert("Something wrong with login")
    }
    ajaxRequest("../php/deletequz.php",'post',postdata,ok,ko);
}

window.onload = function(){
    function isLogin(){
        if(localStorage.hasOwnProperty("UserName")){
            document.getElementById("login").style.display = 'none';
            document.getElementById("login-out").style.display = 'block';
            document.getElementById("profile").style.display = 'block';
            document.querySelector("#profile a").innerHTML = 'User: ' + localStorage.getItem('UserName');
        }
        else{
            document.getElementById("login-out").style.display = 'none';
            document.getElementById("login").style.display = 'block';
            document.getElementById("profile").style.display = 'none';
        }
    }
    isLogin();
    
    function ok(){
        console.log(this.responseText);
        let json_string = this.responseText;
        let res_object = JSON.parse(json_string);
        for(var i = 0; i < res_object.length; i++){
            menu.push(res_object[i].category);
        }
        menu.unshift('all');
        initCategoryMenu();
    }

    function ko(){
        console.log(this.responseText);
        alert("Something wrong with get category");
    }

    function getCategoy(){
        ajaxRequest("../php/getCategory.php", 'get', null, ok, ko);
    }

    function initCategoryMenu(){
        let catmenu = document.getElementById("category_select");
        
        for(var i = 0; i < menu.length; i++)
        {
            var option = document.createElement("option");
            option.setAttribute('value', (i == 0 ? '' : menu[i]));
            option.innerHTML = menu[i];
            catmenu.appendChild(option);
        }
    };
    getCategoy()
    search();
    getName();
}